package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.schedule.IScheduleClient;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.TaskTypeEnum;
import com.heima.model.schedule.dots.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Transactional
@Slf4j
public class WmNewsTaskServiceImpl implements WmNewsTaskService {

    @Autowired
    private IScheduleClient iScheduleClient ;

    @Override
    @Async //别人调用这个方法属于异步调用
    public void addNewsToTask(Integer articleId, Date publishTime) {
        log.info("添加任务到延时队列中----文章id:{}----begin" ,articleId);
        Task task = new Task() ;
        task.setExecuteTime(publishTime.getTime());
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        //task.setTaskId(); 由数据库生成的
        WmNews wmNews = new WmNews();
        wmNews.setId(articleId);
        //对象序列化给到wmNews对象
        task.setParameters(ProtostuffUtil.serialize(wmNews));
        iScheduleClient.addTask(task);
        log.info("添加任务到延时队列中----文章id:{}----end" ,articleId);
    }

    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService ;

    @Scheduled(fixedRate = 10000)  //调用的周期是每1000ms一次 注意在启动类上开启@EnableScheduling
    @Override
    public void scanNewsByTask() {
        log.info("定时任务开始消费task，自动审核文章");

        ResponseResult result = iScheduleClient.pullTask(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(),
                TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        if (result != null && result.getCode().equals(200) && result.getData() != null) {
            String jsonstr = JSON.toJSONString(result.getData());
            Task task = JSON.parseObject(jsonstr, Task.class);
            WmNews wmNews = ProtostuffUtil.deserialize(task.getParameters(), WmNews.class);
            //开始审核文章
            log.info("审核文章："+wmNews.getId().longValue());
            wmNewsAutoScanService.autoScan(wmNews.getId().longValue());

        }

    }
}
